<?php

/**
 * Name: 风险源仓库层
 * User: Silent
 * Date: 2025-09-20
 * Time: 22:45:54
 */

namespace App\Repositories\Safety;

use App\Models\Safety\RiskSource;
use App\Repositories\BaseRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RiskSourceRepository extends BaseRepository
{
    public function __construct(RiskSource $model)
    {
        parent::__construct($model);
    }

    /**
     * 风险列表查询.
     *
     * @param array $inputs
     * @return mixed
     */
    public function list(array $inputs)
    {
        $query = $this->query()->where('employees_id', request('user_id'));

        // 搜索条件
        if (!empty($inputs['searchText']) && !empty($inputs['searchType'])) {
            switch ($inputs['searchType']) {
                case 'location':
                    $query->where('location', 'like', '%' . $inputs['searchText'] . '%');

                    break;
                case 'code':
                    $query->where('id', '=', $inputs['searchText']);

                    break;
                case 'description':
                    $query->where('description', 'like', '%' . $inputs['searchText'] . '%');

                    break;
            }
        }

        // 风险等级筛选
        if (isset($inputs['riskLevel']) && $inputs['riskLevel'] !== '') {
            $riskLevels = [
                '0' => '低风险',
                '1' => '一般风险',
                '2' => '较大风险',
                '3' => '重大风险',
            ];
            if (array_key_exists($inputs['riskLevel'], $riskLevels)) {
                $query->where('risk_level', $riskLevels[$inputs['riskLevel']]);
            }
        }

        // 处理状态筛选
        if (!empty($inputs['processStatus'])) {
            $query->where('status', $inputs['processStatus']);
        }

        // 事故类型筛选
        if (!empty($inputs['accidentType']) && $inputs['accidentType'] !== '0') {
            // 由于accident_type是JSON字段，格式为 [{"key": 9, "value": "坍塌"}]
            // 数据库中key可能是数字类型，需要同时匹配数字和字符串类型
            $query->where(function ($q) use ($inputs) {
                $q->whereRaw("JSON_CONTAINS(accident_type, JSON_OBJECT('key', ?))", [$inputs['accidentType']])
                    ->orWhereRaw("JSON_CONTAINS(accident_type, JSON_OBJECT('key', ?))", [(int) $inputs['accidentType']]);
            });
        }

        // 日期范围筛选
        if (!empty($inputs['startDate'])) {
            $query->whereDate('created_at', '>=', $inputs['startDate']);
        }
        if (!empty($inputs['endDate'])) {
            $query->whereDate('created_at', '<=', $inputs['endDate']);
        }

        // 分页
        $page     = $inputs['page']     ?? 1;
        $pageSize = $inputs['pageSize'] ?? 20;

        return $query->orderBy('id', 'desc')->paginate($pageSize, ['*'], 'page', $page);
    }


    /**
     * 添加风险源.
     *
     * @param array $inputs
     * @return array
     */
    public function addData(array $inputs): array
    {
        try {
            // 新增员工ID
            $inputs['employees_id'] = request('user_id');
            $riskSource = app(RiskSource::class)->create($inputs);

            return [
                'success' => true,
                'message' => '添加成功',
                'data'    => $riskSource,
            ];
        } catch (\Exception $e) {
            Log::channel('risk_source')->error('添加风险源失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '添加失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * 修改风险源.
     *
     * @param array $inputs
     * @return array
     */
    public function saveData(array $inputs): array
    {
        try {
            if (empty($inputs['id'])) {
                return [
                    'success' => false,
                    'message' => 'ID不能为空',
                ];
            }

            $id = $inputs['id'];
            unset($inputs['id']);

            // 检查记录是否存在
            $query = $this->detail($id);;
            if (!$query) {
                return [
                    'success' => false,
                    'message' => '当前风险源不存在',
                ];
            }

            // 新增员工ID
            $inputs['employees_id'] = request('user_id');

            // 处理accident_type数据
            if (isset($inputs['accident_type']) && is_array($inputs['accident_type'])) {
                $inputs['accident_type'] = $inputs['accident_type'];
            }

            $updatedRiskSource = $query->update($inputs);

            return [
                'success' => true,
                'message' => '修改成功',
                'data'    => $updatedRiskSource,
            ];
        } catch (\Exception $e) {
            Log::channel('risk_source')->error('修改风险源失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '修改失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     *  详情
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function detail($id)
    {
        return $this->query()->where('employees_id', request('user_id'))->find($id);
    }

    /**
     *  删除.
     *
     * @param $query
     * @return array
     */
    public function destroy($query)
    {
        try {
            DB::transaction(function () use ($query) {
                $query->delete();
            });

            return [
                'success' => true,
                'message' => '删除成功',
            ];
        } catch (\Exception $e) {
            Log::channel('risk_source')->error('删除风险源失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '删除失败: ' . $e->getMessage(),
            ];
        }
    }
}
